const { Op } = require("sequelize");
const models = require("../../model");
const { APIError } = require("../../rest");

const Categorys = models.ProductCategory;

// 定义商品分类模型
class CategoryModel {
  // 创建分类
  static async create(params) {
    let { name, key } = params;
    const hasCategory = await Categorys.findOne({
      where: {
        name,
      },
    });
    // 判断类别是否已存在
    if (hasCategory) {
      throw new APIError("category: existing", "类别已存在");
    }
    Categorys.create({
      name,
      key,
    });
  }

  // 查询列表
  static async queryList(query) {
    let { name, key } = query;
    let filter = {};
    if (name) {
      Object.assign(filter, { name: { [Op.like]: `%${name}%` } });
    }
    if (key) {
      Object.assign(filter, { key: { [Op.like]: `%${key}%` } });
    }

    const Categorys = await Categorys.findAll({
      where: filter,
      order: [["createdTime", "DESC"]],
    });

    return Categorys;
  }

  // 删除商品
  static async delete(id) {
    const category = await Categorys.findOne({
      where: {
        id,
      },
    });

    if (!category) {
      throw new APIError("category: not_found", "类别不存在！");
    }
    // 软删除类别
    category.destroy();
  }

  // 更新类别
  static async update(params) {
    let { id, name, key } = params;
    // 查询当前商品
    let category = await Categorys.findByPk(id);
    if (!category) {
      throw new APIError("category: not_found", "类别不存在！");
    }
    category.name = name;
    category.key = key;
    category.save();
  }

  static async detail(id) {
    const category = await Categorys.findOne({
      where: {
        id,
      },
    });
    if (!category) {
      throw new APIError("category: not_found", "类别不存在！");
    }

    return category;
  }
}

module.exports = {
  Categorys: CategoryModel,
};
